<?php

namespace app\admin\controller;

use app\common\api\controller\Relation;
use app\common\model\Manager;
use app\common\model\Member;
use app\common\model\MemberPackages;
use think\captcha\Captcha;
use think\Db;

/**
 * 后台首页控制器
 */
class Index extends Home
{

    /**
     * 获取验证码
     * @return \think\Response
     */
    public function makeCaptcha()
    {
        $captcha = new Captcha();
        return $captcha->entry();
    }

    /**
     * 后台首页
     */
    public function index()
    {
        $mid = is_admin_login();
        $mname = Db('manager')->where('mid', $mid)->value('mname');
        $sql = "select sum(income) as income,sum(expend) as expend,sum(bonus1) as bonus1,sum(bonus2) as bonus2 from zx_finance ";
        $alist = Db('finance')->query($sql);


        $list = $this->financeFilter($alist);
        $list[0]['surplus'] = $list[0]['income'] - $list[0]['expend'];

        $this->assign('list', $list[0]);
        $this->assign('mname', $mname);

        $this->assign('title', '首页');
        return $this->fetch();
    }

    /**
     * 拨出比计算
     * @param $list
     * @return mixed
     */
    private function financeFilter($list)
    {
        foreach ($list as &$v) {
            $v['surplus'] = sprintf("%0.2f", $v['income'] - $v['expend']);

            if ($v['income'] == 0) {
                $v['outrate'] = 100.00;
            } else {
                $v['outrate'] = round($v['expend'] / $v['income'], 4) * 100;
            }
        }
        return $list;
    }

    /**
     * 后台用户登录
     */
    public function login($username = null, $password = null)
    {
        if (request()->isPost()) {

            $verify = trim(input('post.verify'));
            if ('' === $verify) {
                $this->error('验证码不能为空');
            }
            if (!captcha_check($verify)) {
                $this->error('验证码错误');
            }

//            $code = input('code');
//            if ($code != session('phone_verify_code')) {
//                $this->error('手机验证码错误');
//            }

            $manager = Db('manager')->where('mname', $username)->find();
            if (!$manager || 1 != $manager['status']) {

                $this->error('管理员不存在或已冻结！');
            }
            /* 调用UC登录接口登录 */
            $managerObj = new Manager();
            $uid = $managerObj->login($manager, $password);
            if (0 < $uid) { //UC登录成功
                /* 登录用户 */
                $this->success('登录成功！', url('Index/index'));
            } else { //登录失败
                switch ($uid) {
                    case -101:
                        $error = '密码错误！';
                        break;
                    default:
                        $error = '未知错误！';
                        break; // 0-接口参数错误（调试阶段使用）
                }
                $this->error($error);
            }
        } else {
            $this->assign('title', '管理员登录');
            return $this->fetch();
        }
    }


    /* 退出登录 */
    public function logout(Manager $manager)
    {
        if (is_admin_login()) {
            $manager->logout();
            $this->success('退出成功！', url('login'));
        } else {
            $this->redirect('login');
        }
    }

    public function verify()
    {
        if (C('VERIFY_TYPE') == 4) {
            $zhset = C('ZH_FONT');
            $zhset = empty($zhset) ? '们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这' : $zhset;
            $config = array(
                'useZh' => true,
                'zhSet' => $zhset,
                'length' => 6,     // 验证码位数
                'useNoise' => false, // 关闭验证码杂点
                'useCurve' => false,
            );
        } else {
            if (C('VERIFY_TYPE') == 1) {
                $codeSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            } elseif (C('VERIFY_TYPE') == 2) {
                $codeSet = '0123456789';
            } else {
                $codeSet = '0123456789ABCDEFGHGKLMNPQRST';
            }
            $config = array(
                'codeSet' => $codeSet,
                'length' => 6,     // 验证码位数
                'fontttf' => '4.ttf',
                'useNoise' => false, // 关闭验证码杂点
                'useCurve' => false,

            );
        }
    }

    /**
     * 自动收货
     */
    public function autoDelivery()
    {
        $orders = Db('shop_order')->field('id,send_time')->where('status', 10)->order('id asc')->select();
        if (!$orders) {
            return;
        }

        $days = 10;
        $times = 86400 * $days;
        $now = time();
        $data = [
            'status' => 20,
            'finish_time' => $now
        ];

        foreach ($orders as $val) {
            if (($val['send_time'] + $times) > $now) {
                continue;
            }

            Db('shop_order')->where('id', $val['id'])->update($data);
            Db('shoplist')->where('orderid', $val['id'])->update($data);
        }
    }

    /**
     * 更换节点人
     */
//    public function changePoint()
//    {
//        $uids = [107];
//        foreach ($uids as $val) {
////            (new Relation())->getPosition($val);
//            $sons = Member::where('parentids', 'like', '%,' . $val . ',%')->where('userrank', '>=', 1)->order('pdeep asc')->select();
//
//            foreach ($sons as $vv) {
//                $pinfo = Member::where('uid', $vv->parentid)->find();
//                $vv->parentid = $pinfo->uid;
//                $vv->parentnumber = $pinfo->usernumber;
//                $vv->parentids = $pinfo->parentids ? $pinfo->parentids . $pinfo->uid . ',' : ',' . $pinfo->uid . ',';
//                $vv->pdeep = $pinfo->pdeep + 1;
//                if ($pinfo->zone_1 == 0) {
//                    $vv->zone = 1;
//                    $vv->zids = $pinfo->zids . '1';
//                    $pinfo->zone_1 = 1;
//                } elseif ($pinfo->zone_2 == 0) {
//                    $vv->zone = 2;
//                    $vv->zids = $pinfo->zids . '2';
//                    $pinfo->zone_2 = 1;
//                } else {
//                    $vv->zone = 3;
//                    $vv->zids = $pinfo->zids . '3';
//                    $pinfo->zone_3 = 1;
//                }
//
//                $vv->save();
//                $pinfo->save();
//            }
//        }
//    }

    public function changePoint()
    {
//        $orders = Db('shop_order')->where('id', '>=', 13)->where('id', '<=', 92)->select();
//        foreach ($orders as $val) {
////            if (!$val['toolid']) {
////                $listInfo = Db('shoplist')->where('orderid', $val['id'])->find();
////                if ($listInfo['toolid']) {
////                    $data = [
////                        'toolid' => $listInfo['toolid'],
////                        'tool' => $listInfo['tool'],
////                        'send_name' => $listInfo['send_name'],
////                        'send_contact' => $listInfo['send_contact'],
////                        'send_address' => $listInfo['send_address'],
////                    ];
////                    Db('shop_order')->where('id', $val['id'])->update($data);
////                }
////            }
//
//            Db('shop_order')->where('id', $val['id'])->update(['tool'=>$val['send_contact'],'send_name'=>$val['send_address'],'send_address'=>$val['tool'],'send_contact'=>$val['toolid']]);
//        }

//        $orders = Db('shop_order')->where('status', '>=', 1)->select();
////        var_dump($orders);die;
//        foreach ($orders as $val) {
//            $user = Db('member')->find($val['uid']);
//            if (!$user['parentid']) {
//                continue;
//            }
//
//            $pid = $this->getCstore($user);
//            if ($pid === false) {
//                continue;
//            }
////            var_dump($pid);die;
//            $total = $val['total'] - 150;
////            var_dump($total);die;
//            Db('member')->where('uid', $pid)->setInc('achievement', $total);
//
//            $item = [
//                'uid' => $pid,
//                'fuid' => $val['uid'],
//                'money' => $total,
//                'create_time' => time(),
//                'update_time' => time(),
//            ];
//            Db('achievement_log')->insert($item);
//        }

    }

    public function getCstore($user)
    {
        if ($user['zone'] == 3) {
            $pid = Member::where('uid', $user['parentid'])->where('status', 1)->value('uid');
            if (!$pid) {
                return false;
            }
        } else {
            $cpinfo = Member::where('uid', 'in', $user['parentids'])->where('zone', 3)->order('pdeep', 'desc')->find();
            if (!$cpinfo) {
                return false;
            }

            $pid = Member::where('uid', $cpinfo->parentid)->value('uid');
        }

        return $pid;
    }
}
